<?php


class Cms_Model_Templates extends WSB_Db_Rowset
{
	/**
	 * @param integer $templateId
	 * @param Zend_View_Interface $view
	 * @return string
	 */
	public function renderHtml($templateId, Zend_View_Interface $view = null)
	{
		$template = $this->_getTemplate($templateId);
		$i = 0;
		$html = $template->html;
		$parentPlaceholder = $template->placeholder_id;
		while($template->pid > 0) {
			$from = '{{' . $parentPlaceholder . '}}';
			switch(intval($template->nesting_mode)) {
				// Replace
				case 0:
					$to = $html;
					break;
				// Append
				case 1:
					$to = '{{' . $parentPlaceholder . '}}' . $html;
					break;
				// Prepend
				case 2:
					$to = $html . '{{' . $parentPlaceholder . '}}';
					break;
			}
			$template = $this->_getTemplate($template->pid);
			$html = str_replace($from, $to, $template->html);
			$parentPlaceholder = $template->placeholder_id;
			if($i>100) die ("Error: Infinite loop in Cms_Model_Templates::renderHtml()");
			$i++;
		}

		// Root (=> $template)
		if($view) {
			$view->headTitle($template->name);
			// Stylesheets in HTML einbinden
			foreach($template->getStylesheets() AS $stylesheet) {
				if($stylesheet->rel == 'stylesheet') {
					$view->headLink()->appendStylesheet($stylesheet->href, $stylesheet->media);
				}
			}
		}

		return $html;
	}

	/**
	 * @param integer $templateId
	 * @return Cms_Model_Template
	 */
	private function _getTemplate($templateId)
	{
		foreach($this AS $template) {
			if($template->id == $templateId) {
				return $template;
			}
		}
	}

}